#include <DTitlebar>
#include <QMouseEvent>
#include <DPlatformWindowHandle>
#include <QPainter>
#include <QBrush>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QIcon>
#include <QPalette>
#include <QScrollBar>
#include <QMapIterator>
#include <DDialog>
#include <DLineEdit>
#include <QHelpEvent>
#include <QToolTip>
#include "MainWindow.h"
#include "TaskList.h"
#include "StateBar.h"
#include "AboutDialog.h"
#include "floatTask/FloatTaskItem.h"

QColor MainWindow::backgroundColor;

MainWindow::MainWindow()
{
    titlebar()->setMenuVisible(false);
    titlebar()->setFixedHeight(0);

    setWindowFlags(Qt::WindowStaysOnBottomHint | Qt::Tool);
    setAttribute(Qt::WA_X11NetWmWindowTypeDock);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_AlwaysShowToolTips);
    setCentralWidget(new QWidget);

    layout = new QVBoxLayout(centralWidget());
    layout->setSpacing(0);

    initDateButtons();
    initTaskList();
    initToolButtons();

    layout->addStretch();

    resize(340, 390);
    move(DataCenter::instance().mainWindowPos);

    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, &MainWindow::onThemeChanged);
    connect(&DataCenter::instance(), &DataCenter::jobsUpdate, this, &MainWindow::refreshTaskList);
    connect(&DataCenter::instance(), &DataCenter::timeUpdate, this, &MainWindow::refreshTaskList);
    connect(&DataCenter::instance(), &DataCenter::jobsUpdate, stateBar, &StateBar::refresh);
    connect(&DataCenter::instance(), &DataCenter::timeUpdate, stateBar, &StateBar::refresh);

    onThemeChanged(DGuiApplicationHelper::instance()->themeType());
    refreshTaskList();

    FloatTaskItem::initFloatTaskItems();
}

bool MainWindow::event(QEvent *event)
{
    QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
    if (mouseEvent)
    {
        lower();
        if (mouseEvent->type() == QEvent::MouseButtonPress)
        {
            movePoint = mouseEvent->windowPos().toPoint();
        }
        if (mouseEvent->type() == QEvent::MouseMove)
        {
            move(mouseEvent->globalPos() - movePoint);
        }
        return true;
    }
    else
    {
        return QWidget::event(event);
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(backgroundColor);
    painter.drawRoundedRect(this->rect(), windowRadius(), windowRadius());
}


void MainWindow::initDateButtons()
{
    homeButton = new DButtonBoxButton(QIcon(":/pics/homepage.svg")); // homepage
    DButtonBoxButton *b1 = new DayButton("D1", this);
    DButtonBoxButton *b2 = new DayButton("D2", this);
    DButtonBoxButton *b3 = new DayButton("D3", this);
    DButtonBoxButton *b4 = new DayButton("D4", this);
    DButtonBoxButton *b5 = new DayButton("D5", this);
    DButtonBoxButton *b6 = new DayButton("D6", this);
    hiddenButton = new DButtonBoxButton("Hidden", this); // use this to uncheck others

    homeButton->setToolTip(tr(" ToDo "));

    homeButton->setIconSize(QSize(20, 20));
    hiddenButton->hide();

    box = new DButtonBox;
    box->setButtonList({homeButton, hiddenButton, b1, b2, b3, b4, b5, b6}, true);
    box->setFixedWidth(280);
    box->setOrientation(Qt::Horizontal);
    box->setAttribute(Qt::WA_NoMousePropagation);

    box->setId(homeButton, 0);
    box->setId(b1, 1);
    box->setId(b2, 2);
    box->setId(b3, 3);
    box->setId(b4, 4);
    box->setId(b5, 5);
    box->setId(b6, 6);

    homeButton->setChecked(true);
    connect(box, &DButtonBox::buttonClicked, this, &MainWindow::onDayButtonClicked);

    stateBar = new StateBar(this);
    stateBar->setFixedSize(280, 5);

    layout->addSpacing(20);
    layout->addWidget(box, 0, Qt::AlignCenter);
    layout->addSpacing(5);
    layout->addWidget(stateBar, 0, Qt::AlignCenter);
}

void MainWindow::initTaskList()
{
    taskList = new TaskList;
    taskScrollArea = new QScrollArea;
    taskScrollArea->setFrameShape(QFrame::NoFrame);
    taskScrollArea->setAttribute(Qt::WA_TranslucentBackground);
    taskScrollArea->setAutoFillBackground(true);
    taskScrollArea->setWidget(taskList);
    taskScrollArea->setFixedHeight(200);

    taskScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    taskScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    taskScrollArea->verticalScrollBar()->setProperty("_d_dtk_slider_always_show", true);

    taskScrollArea->setStyleSheet(R"(
        .TaskList {
            background-color: rgba(0,0,0,0);
        }

        .QScrollArea {
            background-color: rgba(0,0,0,0);
            margin: 0px;
            padding: 0px;
        }

    )");

    layout->addSpacing(25);
    layout->addWidget(taskScrollArea, 0, Qt::AlignCenter);
}

void MainWindow::initToolButtons()
{
    DButtonBoxButton *editButton = new DButtonBoxButton(QIcon(":/pics/edit.svg")); // edit
    createButton = new DButtonBoxButton(QIcon(":/pics/plus.svg")); // plus
    DButtonBoxButton *warnButton = new DButtonBoxButton(QIcon(":/pics/task.svg")); // passed
    DButtonBoxButton *aboutButton = new DButtonBoxButton(QIcon(":/pics/about.svg")); // passed
    DButtonBoxButton *closeButton = new DButtonBoxButton(QIcon(":/pics/close.svg")); // close

    editButton->setToolTip(tr(" Open Calendar "));
    createButton->setToolTip(tr(" Create Floating Task "));
    warnButton->setToolTip(tr(" Previous Tasks "));
    aboutButton->setToolTip(tr(" About "));
    closeButton->setToolTip(tr(" Close "));


    editButton->setIconSize(QSize(20, 20));
    createButton->setIconSize(QSize(25, 25));
    warnButton->setIconSize(QSize(20, 20));
    aboutButton->setIconSize(QSize(20, 20));
    closeButton->setIconSize(QSize(20, 20));

    tools = new DButtonBox;
    tools->setButtonList({editButton, createButton, warnButton, aboutButton, closeButton}, false);
    tools->setFixedWidth(200);
    tools->setAttribute(Qt::WA_NoMousePropagation);

    layout->addSpacing(25);
    layout->addWidget(tools, 0, Qt::AlignCenter);

    connect(editButton, &DButtonBoxButton::clicked, &DataCenter::instance(), &DataCenter::raiseCalendarWindow);

    connect(createButton, &DButtonBoxButton::clicked, this, &MainWindow::onCreateButtonClicked);

    connect(warnButton, &DButtonBoxButton::clicked, this, [this](){
        m_displayInfo = Passed;
        hiddenButton->setChecked(true);
        refreshTaskList();
    });

    connect(aboutButton, &DButtonBoxButton::clicked, this, [=](){
        AboutDialog ad(this);
        ad.exec();
    });

    connect(closeButton, &DButtonBoxButton::clicked, this, [](){
        qApp->exit();
    });


}

void MainWindow::refreshTaskList()
{
    QVector<ScheduleDataInfo> remindTasks;
    DataCenter::instance().getJobs(m_displayInfo, remindTasks);
    taskList->setTasks(remindTasks);
}

void MainWindow::onDayButtonClicked(QAbstractButton *dayButton)
{
    int index = box->id(dayButton);
    assert(index >= 0);
    m_displayInfo = DisplayInfo(index);
    refreshTaskList();
}

void MainWindow::onCreateButtonClicked()
{
    DDialog dd(this);
    dd.setTitle(tr("Create a new floating task"));
    DLineEdit *lineEdit = new DLineEdit;
    lineEdit->setFixedWidth(250);
    dd.addSpacing(30);
    dd.addContent(lineEdit, Qt::AlignCenter);
    dd.addSpacing(20);
    dd.addButton(tr("OK"), true);
    dd.addButton(tr("Cancel"), false);
    lineEdit->setFocus();
    if (dd.exec() == 0 && !lineEdit->text().isEmpty())
    {
        FloatTaskItem *floatTaskItem = new FloatTaskItem;
        floatTaskItem->setTask(lineEdit->text(), false);
        floatTaskItem->move(pos() - QPoint(0, 80));
        floatTaskItem->show();
    }

}

void MainWindow::onThemeChanged(DGuiApplicationHelper::ColorType type)
{
    if (type == DGuiApplicationHelper::ColorType::DarkType)
    {
        backgroundColor = QColor(0, 0, 0, 80);
    }
    else
    {
        backgroundColor = QColor(255, 255,255, 80);
    }
}

MainWindow::~MainWindow()
{

}


bool DayButton::event(QEvent *event)
{
    if (event->type() == QEvent::ToolTip) {
         QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
         if (text().startsWith("D"))
         {
             QToolTip::showText(helpEvent->globalPos(), QDate::currentDate().addDays(text().remove(0, 1).toInt()).toString("MMM dd ddd"));
         }
         else
         {
             QToolTip::hideText();
             event->ignore();
         }

         return true;
     }
     return QAbstractButton::event(event);
}
